package cn.shyouchi.wuguanjia.android.ui.meetting.plan;

import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.miguelbcr.ui.rx_paparazzo.RxPaparazzo;
import com.miguelbcr.ui.rx_paparazzo.entities.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import cn.shyouchi.wuguanjia.android.Global;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.meet.MeetApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.ui.QRCode.QRCodeActivity;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.GlideCircleTransform;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class PlanMeetDetailActivity extends BaseActivity implements BGASortableNinePhotoLayout.Delegate {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.img_header)
    ImageView mImgHeader;
    @BindView(R.id.tv_person_name)
    TextView mTvPersonName;
    @BindView(R.id.tv_apply_res)
    TextView mTvApplyRes;
    @BindView(R.id.tv_meet_name)
    TextView mTvMeetName;
    @BindView(R.id.tv_meet_time)
    TextView mTvMeetTime;
    @BindView(R.id.tv_meet_addr)
    TextView mTvMeetAddr;
    @BindView(R.id.tv_meet_rom)
    TextView mTvMeetRom;
    @BindView(R.id.tv_meet_holder)
    TextView mTvMeetHolder;
    @BindView(R.id.tv_meet_recorder)
    TextView mTvMeetRecorder;
    @BindView(R.id.tv_meet_purpose)
    TextView mTvMeetPurpose;
    @BindView(R.id.textView4)
    TextView mTextView4;
    @BindView(R.id.tv_start_time)
    TextView mTvStartTime;
    @BindView(R.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R.id.tv_meet_content)
    TextView mTvMeetContent;

    @BindView(R.id.textView3)
    TextView mTextView3;
    @BindView(R.id.edit_meet_recorder)
    EditText mEditMeetRecorder;
    @BindView(R.id.photo_snpl)
    BGASortableNinePhotoLayout mPhotoSnpl;
    @BindView(R.id.item_scan_qrcode)
    LinearLayout mItemScanQrcode;


    MeetApi mMeetApi;

    int meetId;
    @BindView(R.id.tv_record)
    TextView mTvRecord;
    @BindView(R.id.item_start)
    LinearLayout mItemStart;
    @BindView(R.id.item_persons)
    LinearLayout mItemPersons;


    MenuItem mSubMenuItem;
    Menu mMenu;

    ArrayList<String> photos = new ArrayList<>();
    @BindView(R.id.tv_qrcode)
    TextView mTvQrcode;


    @Override
    public int initContentView() {
        return R.layout.activity_plan_meet_detail;
    }

    @Override
    public void initInjector() {
        mMeetApi = new MeetApi(mContext);
        meetId = getIntent().getIntExtra("meetId", 0);
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());
        mPhotoSnpl.init(this);
        mPhotoSnpl.setDelegate(this);

        mPhotoSnpl.setIsSortable(false);


    }


    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @OnClick(R.id.item_scan_qrcode)
    public void onClick() {

        if (mTvQrcode.getText().equals("扫描签到")) {
            startActivity(new Intent(mContext, QRCodeActivity.class));

        } else {
            Intent intent = new Intent(mContext, ScanSignMeetActivity.class);
            intent.putExtra("meetId", meetId);
            startActivity(intent);
        }


    }


    private void fetchMeetDetail() {
        mMeetApi.fetchMeetInfo(meetId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult<PlanMeetDetailEntity>>(mContext) {
                    @Override
                    public void onNext(BaseRequestResult<PlanMeetDetailEntity> feedbackDetailEntityBaseRequestResult) {
                        fillData(feedbackDetailEntityBaseRequestResult.getResultMessage());
                    }
                });
    }


    private void fillData(PlanMeetDetailEntity entity) {

        String endtime;
        try {
            endtime = entity.getEnd().substring(11);
        } catch (Exception e) {
            e.printStackTrace();
            endtime = entity.getEnd();
        }


        mTvPersonName.setText(entity.getUsername());
        mTvApplyRes.setText(entity.getState());
        mTvMeetName.setText(entity.getName());
        mTvMeetTime.setText(String.format("%s-%s", entity.getStart(), endtime));
        mTvMeetAddr.setText(entity.getAddress());
        mTvMeetHolder.setText(entity.getHost());
        mTvMeetRecorder.setText(entity.getRecorder());
        mTvMeetPurpose.setText(entity.getMeeting_purpose());
        mTvMeetContent.setText(entity.getMeeting_agenda());
        loadHead(Global.BASE_URL + entity.getId_card_head_image(), mImgHeader);


        if (entity.getPermissions() == 3) {
            mEditMeetRecorder.setVisibility(View.GONE);
            mTvRecord.setVisibility(View.VISIBLE);
            mTvRecord.setText(entity.getRecord());
            mPhotoSnpl.setIsPlusSwitchOpened(false);
            mItemScanQrcode.setVisibility(View.GONE);
            mItemPersons.setVisibility(View.VISIBLE);
            mTvMeetRom.setText(fillPersons(entity.getNumber()));

//            mPhotoSnpl.setData();
            covertImg(entity.getImage());
            mPhotoSnpl.setItemSpanCount(3);
            mPhotoSnpl.setDeleteDrawableResId(R.drawable.photo_del_bg);

        } else if (entity.getPermissions() == 2) {

            mItemStart.setVisibility(View.GONE);
            mTvRecord.setVisibility(View.GONE);
            mPhotoSnpl.setVisibility(View.GONE);
            mPhotoSnpl.setIsPlusSwitchOpened(false);
            mItemScanQrcode.setVisibility(View.GONE);
            mEditMeetRecorder.setVisibility(View.GONE);
            mItemPersons.setVisibility(View.GONE);


        } else if (entity.getPermissions() == 1 && entity.getCheckstatus() == 1) {
            mItemStart.setVisibility(View.VISIBLE);
            mTvRecord.setVisibility(View.GONE);
            mPhotoSnpl.setVisibility(View.VISIBLE);
            mPhotoSnpl.setIsPlusSwitchOpened(true);
            mItemScanQrcode.setVisibility(View.VISIBLE);
            mEditMeetRecorder.setVisibility(View.VISIBLE);
            mItemPersons.setVisibility(View.GONE);
            mMenu.setGroupVisible(mSubMenuItem.getGroupId(), true);
            mEditMeetRecorder.setText(entity.getRecord());
            covertImg(entity.getImage());

        } else {

            mItemStart.setVisibility(View.GONE);
            mTvRecord.setVisibility(View.GONE);
            mPhotoSnpl.setVisibility(View.GONE);
            mPhotoSnpl.setIsPlusSwitchOpened(false);
            mItemScanQrcode.setVisibility(View.VISIBLE);
            mEditMeetRecorder.setVisibility(View.GONE);
            mItemPersons.setVisibility(View.GONE);
            mMenu.setGroupVisible(mSubMenuItem.getGroupId(), false);
            mEditMeetRecorder.setText(entity.getRecord());
            mTvQrcode.setText("扫描签到");
        }


    }


    private void loadHead(String path, ImageView imageView) {
        Glide.with(mContext)
                .load(path)
                .transform(new GlideCircleTransform(mContext))
                .into(imageView);
    }


    private String fillPersons(List<PlanMeetDetailEntity.NumberBean> persons) {
        StringBuffer sb = new StringBuffer();
        if (persons != null) {
            for (PlanMeetDetailEntity.NumberBean p : persons) {
                if (persons.indexOf(p) == persons.size() - 1) {
                    sb.append(p.getUsername());
                } else {
                    sb.append(p.getUsername() + "/");
                }
            }


        }

        return sb.toString();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item == mSubMenuItem) {
            saveMeetRecord();
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mMenu = menu;
        mSubMenuItem = mMenu.add("提交");
        mSubMenuItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        mMenu.setGroupVisible(mSubMenuItem.getGroupId(), false);
        fetchMeetDetail();
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        RxPaparazzo.takeImage(this)
                .useInternalStorage()
                .usingCamera()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<Response<PlanMeetDetailActivity, String>>(mContext) {
                    @Override
                    public void onNext(Response<PlanMeetDetailActivity, String> response) {
                        photos.add(response.data());
                        mPhotoSnpl.setData(photos);
                    }
                });
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotoSnpl.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, mPhotoSnpl.getMaxItemCount(), models, models, position, false), 2);
    }


    private void saveMeetRecord() {
        mMeetApi.addMeetRecord(String.valueOf(meetId), mEditMeetRecorder.getText().toString(), mPhotoSnpl.getData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult<String>>(mContext) {
                    @Override
                    public void onNext(BaseRequestResult<String> result) {
                        ToastUtil.showToast(result.getResultMessage());
                    }
                });

    }

    public void covertImg(List<String> urls) {
        Observable.from(urls)
                .subscribeOn(Schedulers.io())
                .map(new Func1<String, JSONObject>() {
                    @Override
                    public JSONObject call(String s) {
                        try {
                            return new JSONObject(s);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        throw new RuntimeException("Json转换失败");
                    }
                })
                .map(new Func1<JSONObject, String>() {
                    @Override
                    public String call(JSONObject json) {
                        try {
                            return Global.BASE_URL + json.getString("image");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        throw new RuntimeException("Json转换失败");
                    }
                })
                .flatMap(new Func1<String, Observable<String>>() {
                    @Override
                    public Observable<String> call(String url) {
                        return Observable.just(url)
                                .subscribeOn(Schedulers.io())
                                .map(new Func1<String, String>() {
                                    @Override
                                    public String call(String s) {
                                        FutureTarget<File> future = Glide
                                                .with(mContext)
                                                .load(s)
                                                .downloadOnly(500, 500);
                                        try {
                                            File file = future.get();
                                            String path = file.getAbsolutePath();
                                            return path;
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        } catch (ExecutionException e) {
                                            e.printStackTrace();
                                        }
                                        throw new RuntimeException("图片地址无效");
                                    }
                                });


                    }
                }).toList()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<String>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<String> imgs) {
                        photos.addAll(imgs);
                        mPhotoSnpl.setData(photos);
                    }
                });


    }


}
